package com.ruoyi.basis.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mashuai.utils.base.MsEmptyUtils;
import com.mashuai.utils.toolkit.core.msHandlebean.MsHandleDataUtils;
import com.mashuai.utils.toolkit.core.msMp.MsDb;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.validation.annotation.Validated;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 最基础的基类。
 * 保存时候提供一些默认值设置
 *
 * @ClassName: MsBaseController
 * @Author : mashuai
 * @Description: TODO
 */
public class MsBaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> {

    //新增时候需要赋默认值
    private static final String ADD_DEF_FIELD = "create_id;create_by;create_time";
    private static final String UPDATE_DEF_FIELD = "update_id;update_by;update_time";

    /***
     * 插入
     */
    public boolean insertData(@Validated T entity) {
        setDefFieldVal(entity, true);
        return MsDb.save(entity);
    }

    /***
     * 更新
     */
    public boolean updateData(@Validated T entity) {
        setDefFieldVal(entity, false);
        return MsDb.updateById(entity);
    }


    /**
     * 删除前的校验是否被其他表进行引用，需要结合@MsDelCheck
     *
     * @param ids 删除的id集合
     * @param clz 类对象
     **/
    public <M> void delCheck(List ids, Class<T> clz) {
        MsHandleDataUtils.handleDelCheck(ids, clz);
    }

    public <M> void delCheck(M ids[], Class<T> clz) {
        List<M> bizIds = new ArrayList<>();
        for (M id : ids) {
            bizIds.add(id);
        }
        MsHandleDataUtils.handleDelCheck(bizIds, clz);
    }


    /**
     * 保存校验某些字段值是否重复 实体字段加上该注解@MsSaveCheck
     **/
    public void saveCheck(T m) {
        try {
            MsHandleDataUtils.handleSaveCheck(m);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 注意根据id值是否为空判断是新增还是修改
     **/
    public void setDefFieldVal(T entity) {
        String id = entity.getId();
        if (MsEmptyUtils.isNotEmpty(id)) {
            setDefFieldVal(entity, false);
        } else {
            setDefFieldVal(entity, true);
        }
    }


    /**
     * 设置一些默认字段值。后面优化可把字段缓存起来
     **/
    public void setDefFieldVal(T entity, boolean isAdd) {
        Field[] fields = entity.getClass().getSuperclass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                //新增，赋值默认的 create_id，create_by，create_time
                if (isAdd) {
                    if ("createId".equals(name)) {
                        field.set(entity, SecurityUtils.getUserId());
                    } else if ("createBy".equals(name)) {
                        //field.set(entity, SecurityUtils.getUsername());
                    } else if ("createTime".equals(name)) {
                        field.set(entity, new Date());
                    }
                }
                //更新，赋值默认的 update_id，update_by，update_time
                else {
                    if ("updateId".equals(name)) {
                        field.set(entity, SecurityUtils.getUserId());
                    } else if ("updateBy".equals(name)) {
                       // field.set(entity, SecurityUtils.getUsername());
                    } else if ("updateTime".equals(name)) {
                        field.set(entity, new Date());
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


}
